package net.zdsoft.wpchat.support.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.zdsoft.keel.action.ActionContext;
import net.zdsoft.keel.action.Messageable;
import net.zdsoft.keel.page.PageStyle;
import net.zdsoft.keel.util.ActionUtils;
import net.zdsoft.keel.util.DateUtils;
import net.zdsoft.keel.util.Pagination;
import net.zdsoft.keel.util.ServletUtils;
import net.zdsoft.keel.util.StringUtils;
import net.zdsoft.keel.util.URLUtils;
import net.zdsoft.wpchat.support.client.MemoryUser;
import net.zdsoft.wpchat.support.client.UserAuth;
import net.zdsoft.wpchat.support.entity.UserOperation;

/**
 * 页面工具类
 *
 * @author xuan
 */
public final class PageUtils {
    private static final PageStyle pageStyle = new PageStyle();

    static {
        pageStyle.setActionMessageStyle("", "<span>", "</span>", "");
    }

    private PageUtils() {
    }

    public static Object getFirstAction() {
        return ActionUtils.getFirstAction();
    }

    public static Object getLastAction() {
        return ActionUtils.getLastAction();
    }

    public static Object getAction() {
        return getLastAction();
    }

    public static Object getAction(String actionName) {
        return ActionUtils.getAction(actionName);
    }

    public static boolean isPost(HttpServletRequest request) {
        return ServletUtils.isPost(request);
    }

    public static String firstError(Messageable action) {
        return ActionUtils.firstActionError(action, pageStyle);
    }

    public static String errors() {
        return ActionUtils.actionErrors(pageStyle);
    }

    public static String errors(Messageable action) {
        return ActionUtils.actionErrors(action, pageStyle);
    }

    public static String allErrors(Messageable action) {
        return ActionUtils.allErrors(action, pageStyle);
    }

    public static Object ignoreNull(Object value) {
        return (value == null) ? "" : value;
    }

    public static String pagination(String url, Pagination page) {
        return pagination(url, page, false);
    }

    public static String paginationForAjax(String url, String partId, Pagination page, boolean needJump) {
        if (page == null) {
            return "";
        }

        StringBuffer pagination = new StringBuffer();
        final String separator = "&nbsp;&nbsp;";

        if (page.getPageIndex() > page.getMaxPageIndex()) {
            page.setPageIndex(page.getMaxPageIndex());
        }

        pagination.append("共" + page.getMaxRowCount() + "条记录");
        pagination.append(separator);
        pagination.append("这是" + page.getPageIndex() + "/" + page.getMaxPageIndex() + "页");
        // pagination.append(separator);
        // pagination.append("每页" + rowsPerPage + "条记录");
        pagination.append(separator);

        if (page.getPageIndex() > 1) {
            pagination.append("<a class=\"pagination\" href=\"javascript:void(0);\""
                    + " onclick=\"javascript:$('#"
                    + partId
                    + "').load('"
                    + URLUtils.addQueryString(url, new String[] { "pageIndex", "pageSize" },
                            new Object[] { "1", page.getPageSize() }) + "');return false;\">首页</a>");
            pagination.append(separator);
            pagination.append("<a class=\"pagination\" href=\"javascript:void(0);\""
                    + " onclick=\"javascript:$('#"
                    + partId
                    + "').load('"
                    + URLUtils.addQueryString(url, new String[] { "pageIndex", "pageSize" },
                            new Object[] { String.valueOf(page.getPageIndex() - 1), page.getPageSize() })
                    + "');return false;\">上一页</a>");
            pagination.append(separator);
        }
        else {
            pagination.append("首页");
            pagination.append(separator);
            pagination.append("上一页");
            pagination.append(separator);
        }

        if (page.getPageIndex() < page.getMaxPageIndex()) {
            pagination.append("<a class=\"pagination\" href=\"javascript:void(0);\""
                    + " onclick=\"javascript:$('#"
                    + partId
                    + "').load('"
                    + URLUtils.addQueryString(url, new String[] { "pageIndex", "pageSize" },
                            new Object[] { String.valueOf(page.getPageIndex() + 1), page.getPageSize() })
                    + "');return false;\">下一页</a>");
            pagination.append(separator);
            pagination.append("<a class=\"pagination\" href=\"javascript:void(0);\""
                    + " onclick=\"javascript:$('#"
                    + partId
                    + "').load('"
                    + URLUtils.addQueryString(url, new String[] { "pageIndex", "pageSize" },
                            new Object[] { String.valueOf(page.getMaxPageIndex()), page.getPageSize() })
                    + "');return false;\">末页</a>");
            pagination.append(separator);
        }
        else {
            pagination.append("下一页");
            pagination.append(separator);
            pagination.append("末页");
            pagination.append(separator);
        }

        if (needJump) {
            pagination.append("第 <input id=\"targetPageIndex\" type=\"text\"" + " size=\"3\" maxlength=\"6\" value=\""
                    + page.getPageIndex() + "\" onfocus=\"this.value = ''\""
                    + " onkeyup=\"if (event.keyCode == 13) {jumpPage();}\"> 页");
            pagination.append("&nbsp;&nbsp;每页<input id=\"numPerPage\" type=\"text\" disabled class=\"bInput\""
                    + " size=\"1\" maxlength=\"3\" value=\"" + page.getPageSize() + "\" onfocus=\"this.value = ''\""
                    + " onkeyup=\" if(event.keyCode==13){jumpPage();}\" />条\n");
            pagination.append(" <a href=\"javascript:jumpPage()\">跳转</a>");

            pagination.append("<script language=\"javascript\">\n");
            pagination.append("function jumpPage() {\n");
            pagination.append("    var jumpPageIndex =" + " document.getElementById('targetPageIndex').value;\n");

            pagination.append("    if (isNaN(parseInt(jumpPageIndex))) {\n");
            pagination.append("        alert(\"请输入要跳转的页码\");\n");
            pagination.append("        return;\n");
            pagination.append("    }\n");

            pagination.append("var numPerPage = document.getElementById('numPerPage').value;\n");
            pagination.append("     if(isNaN(parseInt(numPerPage))){\n");
            pagination.append("     numPerPage = " + page.getPageSize() + ";\n");
            pagination.append("    }\n");
            pagination.append(" if(parseInt(numPerPage)<=0){\n");
            pagination.append("     numPerPage = " + page.getPageSize() + ";\n");
            pagination.append("    }\n");
            if (url.indexOf("?") == -1) {
                pagination.append("    $(\"#" + partId + "\").load(\"" + url
                        + "?pageIndex=\" + jumpPageIndex + \"&pageSize=\"+numPerPage" + ");\n");
            }
            else {
                pagination.append("   $(\"#" + partId + "\").load(\"" + url
                        + "&pageIndex=\" + jumpPageIndex + \"&pageSize=\"+numPerPage" + ");\n");
            }

            pagination.append("}\n");
            pagination.append("</script>\n");
        }

        return pagination.toString();
    }

    public static String pagination(String url, Pagination page, boolean needJump) {
        if (page == null) {
            return "";
        }

        StringBuffer pagination = new StringBuffer();
        final String separator = "&nbsp;&nbsp;";

        String sortString = "";

        if (page.getPageIndex() > page.getMaxPageIndex()) {
            page.setPageIndex(page.getMaxPageIndex());
        }

        pagination.append("共" + page.getMaxRowCount() + "条记录");
        pagination.append(separator);
        pagination.append("这是" + page.getPageIndex() + "/" + page.getMaxPageIndex() + "页");
        // pagination.append(separator);
        // pagination.append("每页" + rowsPerPage + "条记录");
        pagination.append(separator);

        if (page.getPageIndex() > 1) {
            pagination.append("<a href=\"" + URLUtils.addQueryString(url, "pageIndex", "1") + sortString + "\">首页</a>");
            pagination.append(separator);
            pagination.append("<a href=\""
                    + URLUtils.addQueryString(url, "pageIndex", String.valueOf(page.getPageIndex() - 1)) + sortString
                    + "\">上一页</a>");
            pagination.append(separator);
        }
        else {
            pagination.append("首页");
            pagination.append(separator);
            pagination.append("上一页");
            pagination.append(separator);
        }

        if (page.getPageIndex() < page.getMaxPageIndex()) {
            pagination.append("<a href=\""
                    + URLUtils.addQueryString(url, "pageIndex", String.valueOf(page.getPageIndex() + 1)) + sortString
                    + "\">下一页</a>");
            pagination.append(separator);
            pagination.append("<a href=\""
                    + URLUtils.addQueryString(url, "pageIndex", String.valueOf(page.getMaxPageIndex())) + sortString
                    + "\">末页</a>");
            pagination.append(separator);
        }
        else {
            pagination.append("下一页");
            pagination.append(separator);
            pagination.append("末页");
            pagination.append(separator);
        }

        if (needJump) {
            pagination.append("第 <input id=\"targetPageIndex\" type=\"text\"" + " size=\"3\" maxlength=\"6\" value=\""
                    + page.getPageIndex() + "\" onfocus=\"this.value = ''\""
                    + " onkeyup=\"if (event.keyCode == 13) {jumpPage();}\"> 页");
            pagination.append(" <a href=\"javascript:jumpPage()\">跳转</a>");

            pagination.append("<script language=\"javascript\">\n");
            pagination.append("function jumpPage() {\n");
            pagination.append("    var jumpPageIndex =" + " document.getElementById('targetPageIndex').value;\n");

            pagination.append("    if (isNaN(parseInt(jumpPageIndex))) {\n");
            pagination.append("        alert(\"请输入要跳转的页码\");\n");
            pagination.append("        return;\n");
            pagination.append("    }\n");

            if (url.indexOf("?") == -1) {
                pagination.append("    location.href = \"" + url + "?pageIndex=\" + jumpPageIndex;\n");
            }
            else {
                pagination.append("    location.href = \"" + url + "&pageIndex=\" + jumpPageIndex;\n");
            }

            pagination.append("}\n");
            pagination.append("</script>\n");
        }

        return pagination.toString();
    }

    public static String drawNavigator() {
        UserAuth auth = getUserAuth();
        if (auth == null) {
            return "";
        }

        return auth.drawNavigator();
    }

    public static String drawTitle() {
        UserAuth auth = getUserAuth();
        if (auth == null) {
            return "";
        }

        return auth.drawTitle();
    }

    public static String getModuleTarget(UserOperation userOperation) {
        if (userOperation == null) {
            return "";
        }

        String actionTarget = userOperation.getDefaultAction();
        if (actionTarget.indexOf(".") >= 0) {
            actionTarget = ActionContext.getRequest().getContextPath() + StringUtils.replace(actionTarget, ".", "/");
        }
        else {
            actionTarget = ActionContext.getRequest().getContextPath()
                    + userOperation.getUserModule().getUserCatalog().getCatalog().getNamespace() + "/" + actionTarget;
        }

        String moduleTarget = actionTarget + ".htm";
        return moduleTarget;
    }

    public static String getDate(Date date) {
        if (date == null) {
            return "";
        }

        return DateUtils.date2StringByDay(date);
    }

    public static String getState() {
        return StringUtils.ignoreNull(ActionContext.getRequest().getParameter("state"));
    }

    public static boolean isSuccessState() {
        return "1".equals(getState());
    }

    public static String successMessage(String message) {
        return isSuccessState() ? "<span>" + message + "</span>" : "";
    }

    public static String messages() {
        return ActionUtils.actionMessages(pageStyle);
    }

    public static UserAuth getUserAuth() {
        return (UserAuth) ActionContext.getRequest().getAttribute(UserAuth.KEY);
    }

    public static MemoryUser getMemoryUser() {
        return (MemoryUser) ActionContext.getSession().getAttribute(MemoryUser.KEY);
    }

}
